//package medicalApp.velociraptors.com;

import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JSlider;
import javax.swing.JTextArea;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

/**
* The UserView class allows for the viewing of a User and all of its information.
*
* @author lsun
*/
@SuppressWarnings("serial")
public class UserView extends JDialog {

	/**
	 * The slider that adjusts the font size.
	 */ 
	private final JSlider slider;
	
	/**
	 * Determines the font size
	 */ 
	protected int fontSize;
	
	/**
	 * Displays the Patient's info.
	 */ 
	private JTextArea txtPatientInfo;
	
	/**
	 * Patient's SSN
	 */ 
	private final int SSN;
	
	/**
	 * The MedAppController that drives the file.
	 */ 
	@SuppressWarnings("unused")
	private MedAppController mac;
	
	/**
	 * The database connection.
	 */ 
	private Connection con;
	
	/**
	 * Date of Birth.
	 */ 
	@SuppressWarnings("unused")
	private String dob;
	
	/**
	 * The patient's username
	 */ 
	@SuppressWarnings("unused")
	private String username;
	
	/**
	 * The patient's firstName
	 */ 
	@SuppressWarnings("unused")
	private String firstName;
	
	/**
	 * The patient's lastName
	 */ 
	@SuppressWarnings("unused")
	private String lastName;
	
	/**
	 * Determines whether the patient's account is suspended
	 */ 
	@SuppressWarnings("unused")
	private int suspended;
	
	/**
	 * The user's user type
	 */ 
	@SuppressWarnings("unused")
	private String type;
	
	/**
	 * The patient's address
	 */ 
	@SuppressWarnings("unused")
	private String address;
	
	/**
	 * The patient's phone number
	 */ 
	@SuppressWarnings("unused")
	private long phoneNumber;
	
	/**
	 * The patient's email address
	 */ 
	@SuppressWarnings("unused")
	private String email;
	
	/**
	 * The patient's gender
	 */ 
	@SuppressWarnings("unused")
	private int gender;
	
	/**
	 * The patient's age
	 */ 
	@SuppressWarnings("unused")
	private int age;
	
	/**
	 * Represents the prescription
	 */ 
	@SuppressWarnings("unused")
	private final ArrayList<String> prescription;
	
	/**
	 * Represents blood test results
	 */ 
	@SuppressWarnings("unused")
	private final ArrayList<Integer> bloodTest;
	
	/**
	 * Represents urine test results
	 */ 
	@SuppressWarnings("unused")
	private final ArrayList<Integer> urineTest;
	
	/**
	 * Represents immunization records
	 */ 
	@SuppressWarnings("unused")
	private final ArrayList<Integer> immuno;
	
	/**
	 * Represents doctorOrders
	 */ 
	@SuppressWarnings("unused")
	private final ArrayList<String> instructions;
	
	/**
	 * Represents the doctor's first name
	 */ 
	private final ArrayList<String> t_doctorFirstName;
	
	/**
	 * Represents the doctor's last name
	 */ 
	private final ArrayList<String> t_doctorLastName;
	
	/**
	 * Represents the date and time of treatment
	 */ 
	private final ArrayList<String> t_dateAndTime;
	
	/**
	 * Represents the first name of the treating nurse
	 */ 
	private final ArrayList<String> t_nurseFirstName;
	
	/**
	 * Represents the last name of the treating nurse
	 */ 
	private final ArrayList<String> t_nurseLastName;
	
	/**
	 * Represents the symptoms
	 */ 
	private final ArrayList<String> t_symptoms;
	
	/**
	 * Systolic blood pressure
	 */ 
	private final ArrayList<Integer> t_bp_s;
	
	/**
	 * Diastolic blood pressure
	 */ 
	private final ArrayList<Integer> t_bp_d;
	
	/**
	 * Measured temperature
	 */ 
	private final ArrayList<Double> t_temp;
	
	/**
	 * Measured height
	 */ 
	private final ArrayList<Double> t_height;
	
	/**
	 * Measured weight
	 */ 
	private final ArrayList<Double> t_weight;
	
	/**
	 * Given diagnosis
	 */ 
	private final ArrayList<String> t_diagnosis;
	
	/**
	 * Output string
	 */ 
	private String output;

	private int count1;

	private int count2;

	private int count3;

	private int count4;

	private int count5;

	/**
	 * Create the dialog.
	 * 
	 * @param mac The MedAppController object that drives the class.
	 * @param currentSSN The patient's SSN
	 * @param drSSN The doctor's SSN
	 */
	public UserView(final MedAppController mac, int currentSSN, final int drSSN) {
		count1=0;
		count2=0;
		count3=0;
		count4=0;
		count5=0;
		SSN = currentSSN; 
		this.mac = mac;
		dob = "";
		username = "";
		firstName = "";
		lastName = "";
		suspended = 0;
		type = "";
		address = "";
		phoneNumber = 0l;
		email = "";
		gender = 0;
		age = 0;
		prescription = new ArrayList<String>();
		bloodTest = new ArrayList<Integer>();
		urineTest = new ArrayList<Integer>();
		immuno = new ArrayList<Integer>();
		instructions = new ArrayList<String>();
		t_doctorFirstName = new ArrayList<String>();
		t_doctorLastName = new ArrayList<String>();
		t_dateAndTime = new ArrayList<String>();
		t_nurseFirstName = new ArrayList<String>();
		t_nurseLastName = new ArrayList<String>();
		t_symptoms = new ArrayList<String>();
		t_bp_s = new ArrayList<Integer>();
		t_bp_d = new ArrayList<Integer>();
		t_temp = new ArrayList<Double>();
		t_height = new ArrayList<Double>();
		t_weight = new ArrayList<Double>();
		t_diagnosis = new ArrayList<String>();
		con = mac.getCon();
		
		final String sql1 = "SELECT * FROM `user` WHERE `U_SSN` = '"+SSN+"'";
		mac.out.println(sql1);

		final String sql2 = "SELECT `DOB` FROM `patients` WHERE `P_SSN`='"+SSN+"'";
		mac.out.println(sql2);

		final String sql3 = "SELECT * FROM `doctorsorders` where `DO_FORPATIENTSSN` = '"+SSN+"'";
		mac.out.println(sql3);

		final String sql4 = "SELECT * FROM `treatmentrecord` where `T_FORPATIENTSSN` = '"+SSN+"'"; 
		mac.out.println(sql4);
		
		final String sql5 = "SELECT * FROM `patient_information` where `FOR_PATIENTSSN` = '"+SSN+"'"; 
		mac.out.println(sql5);

//		final String sql5 = "CREATE OR REPLACE ALGORITHM = TEMPTABLE VIEW  `patient_user_dob_information_doctorsorders_view` AS SELECT  `SSN` ,  `DOB` ,  `USERNAME` ,  `PASSWORD` ,  `U_FIRSTNAME` ,  `U_LASTNAME` ,  `SUSPENDED` ,  `ADDRESS` ,  `PHONE` ,  `EMAIL` ,  `GENDER` , `AGE` ,  `PRESCRIPTION` ,  `BLOOD_TESTS` ,  `URINE_TESTS` ,  `IMMUNIZATIONS` ,  `INSTRUCTIONS`, `DoctorsOrders_ID` FROM  `doctorsorders` JOIN  `patient_user_dob_information_view` ON  `DO_FORPATIENTSSN` =  `patient_user_dob_information_view`.`SSN`;";
//
//		final String sql6 = "CREATE OR REPLACE ALGORITHM = TEMPTABLE VIEW  `patient_user_dob_information_doctorsorders_treatmentrecord_view` AS SELECT  `SSN` ,`DoctorsOrders_ID`,`T_ID`,  `DOB` ,  `USERNAME` ,  `PASSWORD` ,  `U_FIRSTNAME` ,  `U_LASTNAME` ,  `SUSPENDED` ,  `ADDRESS` ,  `PHONE` , `EMAIL`,  `GENDER` ,  `AGE` ,  `PRESCRIPTION` ,  `BLOOD_TESTS` ,  `URINE_TESTS` ,  `IMMUNIZATIONS` ,  `INSTRUCTIONS` ,  `T_DOCTORFIRSTNAME` ,  `T_DOCTORLASTNAME` ,  `T_DATEANDTIME` , `T_NURSEFIRSTNAME` ,  `T_NURSELASTNAME` ,  `T_SYMPTOMS` ,  `T_BP_S`,`T_BP_D`,  `T_PULSE`,  `T_TEMPERATURE` ,  `T_HEIGHT` ,  `T_WEIGHT` ,  `T_DIAGNOSIS` FROM  `treatmentrecord` LEFT JOIN  `patient_user_dob_information_doctorsorders_view` ON  `T_FORPATIENTSSN` =  `patient_user_dob_information_doctorsorders_view`.`SSN`;";
//
//		String sql7 = "SELECT * FROM `patient_user_dob_information_doctorsorders_treatmentrecord_view` WHERE `SSN`='" + currentSSN + "' AND `T_ID`=`DoctorsOrders_ID`";
//		mac.out.println(sql7);
		try {
			Statement stmt1 = con.createStatement();
			Statement stmt2 = con.createStatement();
			Statement stmt3 = con.createStatement();
			Statement stmt4 = con.createStatement();
			Statement stmt5 = con.createStatement();
//			Statement stmt6 = con.createStatement();
//			Statement stmt7 = con.createStatement();
			
			ResultSet rs1 = stmt1.executeQuery(sql1);
			ResultSet rs2 = stmt2.executeQuery(sql2);
			ResultSet rs3 = stmt3.executeQuery(sql3);
			ResultSet rs4 = stmt4.executeQuery(sql4);
			ResultSet rs5 = stmt5.executeQuery(sql5);
//			stmt = stmt6.executeUpdate(sql6);
//			ResultSet rs = stmt7.executeQuery(sql7);
			
			
			while(rs1.next()){
				username = rs1.getString("USERNAME");
				firstName = rs1.getString("U_FIRSTNAME");
				lastName = rs1.getString("U_LASTNAME");
				suspended = rs1.getInt("SUSPENDED");
				type = rs1.getString("USERTYPE");
				count1++;
			}
			while(rs2.next()){
				dob = rs2.getString("DOB");
				count2++;
			}
			
			while(rs3.next()){
				prescription.add(rs3.getString("PRESCRIPTION"));
				bloodTest.add(rs3.getInt("BLOOD_TESTS"));
				urineTest.add(rs3.getInt("URINE_TESTS"));
				immuno.add(rs3.getInt("IMMUNIZATIONS"));
				instructions.add(rs3.getString("INSTRUCTIONS"));
				count3++;
			}
			
			while(rs4.next()){
				t_doctorFirstName.add(rs4.getString("T_DOCTORFIRSTNAME"));
				t_doctorLastName.add(rs4.getString("T_DOCTORLASTNAME"));
				t_dateAndTime.add(rs4.getString("T_DATEANDTIME"));
				t_nurseFirstName.add(rs4.getString("T_NURSEFIRSTNAME"));
				t_nurseLastName.add(rs4.getString("T_NURSELASTNAME"));
				t_symptoms.add(rs4.getString("T_SYMPTOMS"));
				t_bp_s.add(rs4.getInt("T_BP_S"));
				t_bp_d.add(rs4.getInt("T_BP_D"));
				t_temp.add(rs4.getDouble("T_TEMPERATURE"));
				t_height.add(rs4.getDouble("T_HEIGHT"));
				t_weight.add(rs4.getDouble("T_WEIGHT"));
				t_diagnosis.add(rs4.getString("T_DIAGNOSIS"));
				count4++;
				
			}
			while(rs5.next()){
				address = rs5.getString("ADDRESS");
				phoneNumber = rs5.getLong("PHONE");
				email = rs5.getString("EMAIL");
				gender = rs5.getInt("GENDER");
				age = rs5.getInt("AGE");
				count5++;
			}

			String fullName ="Name: " + firstName + " " + lastName + "\n";
			mac.out.println(fullName);

			String userSuspended="";
			if(suspended == 0)
				 userSuspended = username + " is not suspended." + "\n";
			else
				userSuspended = username + " is suspended!" + "\n";
			
			mac.out.println(userSuspended);
			
			String contact = "Contact Information: \n" + address + "\n" + phoneNumber + "\n" + email + "\n";
			mac.out.println(contact);
			
			String bioData = "";
			if(gender == 0)
				bioData = "Biodata: \n Age: " + age + "\n Gender: Male" + "\n";
			else
				bioData = "Biodata: \n Age: " + age + "\n Gender: Female" + "\n";
			mac.out.println(bioData);
			
			String treatmentRecords = "";
			String doctorsOrders = "";
			

//			mac.out.println("treatment record count: " + count);
			for(int i = 0;i < count3;i++){

				treatmentRecords+= "\n";
				treatmentRecords+="Prescription: "+prescription.get(i)+"\n";
				
				if(bloodTest.get(i)==0){
					treatmentRecords+="Blood Test Performed: Yes \n";
				}
				else{
					treatmentRecords+="Blood Test Performed: Yes \n";
				}

				if(urineTest.get(i)==0){
					treatmentRecords+="Urine Test Performed: Yes \n";
				}
				else{
					treatmentRecords+="Urine Test Performed: Yes \n";
				}
				
				if(immuno.get(i)==0){
					treatmentRecords+="Immunizations: Yes \n";
				}
				else{
					treatmentRecords+="Immunizations: Yes \n";
				}
				
			}
			
			for(int i = 0; i<count4;i++){
				treatmentRecords+=instructions.get(i)+"\n";
				
				treatmentRecords += "\n";

				treatmentRecords += "Doctor Name: " + t_doctorFirstName.get(i) + " " + t_doctorLastName.get(i) + "\n";
				treatmentRecords += "Attending Nurse: " + t_nurseFirstName.get(i) + " " + t_nurseLastName.get(i) + "\n";
				treatmentRecords += "Date: " + t_dateAndTime.get(i) + "\n";
				treatmentRecords += "Symptoms: " + t_symptoms.get(i) + "\n";
				treatmentRecords += "Blood Pressure: \n Systolic: " + t_bp_s.get(i) + " Diastolic: " + t_bp_d.get(i) + "\n";
				treatmentRecords += "Temperature: " + t_temp.get(i) + " F \n";
				treatmentRecords += "Height: " + t_height.get(i) + "\n Weight: " + t_weight.get(i) + "\n";
				treatmentRecords += "Diagnosis: " + t_diagnosis.get(i);
				treatmentRecords += "\n";
			}
			output = fullName + userSuspended + contact + bioData + treatmentRecords;
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		setResizable(false);
		setBounds(100, 100, 640, 480);
		getContentPane().setLayout(null);
		
		final JScrollPane scrollPane = new JScrollPane();
		scrollPane.setBounds(10, 11, 604, 380);
		getContentPane().add(scrollPane);
		
		txtPatientInfo = new JTextArea(output);
		txtPatientInfo.setWrapStyleWord(true);
		txtPatientInfo.setLineWrap(true);
		scrollPane.setViewportView(txtPatientInfo);
		txtPatientInfo.setFont(new Font("Monospaced", Font.PLAIN, 14));
		txtPatientInfo.setEditable(false);
		
		final JButton btnAddTreatment = new JButton("Add Treatment");
		btnAddTreatment.addActionListener(new ActionListener() {
			/**
			 * Designed to perform the action specified upon triggering.
			 * 
			 * @param arg0 The ActionEvent that triggers the method call.
			 */ 
			public void actionPerformed(ActionEvent arg0) {
				if (type.equals("Patient")){
					PatientTreatmentDialogAdmin ptd = new PatientTreatmentDialogAdmin(mac,SSN, drSSN);
					ptd.setVisible(true);
				} else JOptionPane.showMessageDialog(null, "Action Not Valid!");
			}
		});
		
		btnAddTreatment.setBounds(495, 408, 119, 23);
		getContentPane().add(btnAddTreatment);
		
		slider = new JSlider();
		slider.setMinimum(10);
		slider.addChangeListener(new ChangeListener() {
			/**
			 * Designed to perform the action specified upon triggering by StateChange.
			 * 
			 * @param arg0 The ChangeEvent that triggers the method call.
			 */ 
			public void stateChanged(ChangeEvent arg0) {
				JSlider source = (JSlider)arg0.getSource();
				
				if(!source.getValueIsAdjusting()){
					fontSize = (int)source.getValue();
					mac.out.println("Font Size set to: " + fontSize);
					txtPatientInfo.setFont(new Font("Monospaced", Font.PLAIN, fontSize));
				}
			}
		});
		slider.setValue(12);
		slider.setSnapToTicks(true);
		slider.setPaintTicks(true);
		slider.setPaintLabels(true);
		slider.setMaximum(30);
		slider.setMajorTickSpacing(2);
		slider.setBounds(74, 402, 262, 35);
		getContentPane().add(slider);
		
		final JLabel lblTextSize = new JLabel("Text Size:");
		lblTextSize.setBounds(20, 412, 62, 14);
		getContentPane().add(lblTextSize);
		
		final JButton btnNewButton = new JButton("Set Password");
		btnNewButton.addActionListener(new ActionListener() {
			/**
			 * Designed to perform the action specified upon triggering.
			 * 
			 * @param arg0 The ActionEvent that triggers the method call.
			 */ 
			public void actionPerformed(ActionEvent arg0) {
				String pass = JOptionPane.showInputDialog(null, "Enter New Password: ");
				if (pass == null) return;
				char[] pa = pass.toCharArray();
				for (int i = 0; i < pa.length; i++) pa[i] += 7;
				String newPass = "";
				for (int i = pa.length - 1; i >= 0; i--) newPass += ((Character)pa[i]).toString();
				pass = newPass;
				System.err.print("new pass " + pass);
				try {
					
					String sql = "UPDATE `user` SET `PASSWORD`='" + pass + "' WHERE `U_SSN` = '" + SSN + "'";
					mac.out.println(sql);
					Connection con = mac.getCon();
					Statement stmt = con.createStatement();
					int rs = stmt.executeUpdate(sql);
					JOptionPane.showMessageDialog(null, "Password Changed!");
					mac.setSysAdminPatientTableModel();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
		btnNewButton.setBounds(349, 408, 126, 23);
		getContentPane().add(btnNewButton);
		
		final JButton btnNewButton_1 = new JButton("Suspend/Unsuspend");
		btnNewButton_1.addActionListener(new ActionListener() {
			/**
			 * Designed to perform the action specified upon triggering.
			 * 
			 * @param arg0 The ActionEvent that triggers the method call.
			 */ 
			public void actionPerformed(ActionEvent arg0) {
				int dialog = JOptionPane.showConfirmDialog(null, "Do you want to suspend/unsuspend this user?");
				if(dialog == JOptionPane.YES_OPTION){

					try {
						if (SSN != 123456786) {
							if (suspended == 0) suspended = 1;
							else suspended = 0;
							String sql = "UPDATE `user` SET `SUSPENDED`='" + suspended + "' WHERE `U_SSN` = '" + SSN + "'";
							mac.out.println(sql);
							Connection con = mac.getCon();
							Statement stmt = con.createStatement();
							int rs = stmt.executeUpdate(sql);
							if (suspended == 0)JOptionPane.showMessageDialog(null, "User Unsuspended!");
							else JOptionPane.showMessageDialog(null, "User Suspended!");
							mac.setSysAdminPatientTableModel();
						} else {
							JOptionPane.showMessageDialog(null, "Action Not Valid");
						}
					} catch (SQLException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		});
		btnNewButton_1.setBounds(395, 442, 177, 23);
		getContentPane().add(btnNewButton_1);
	}
}